const express = require('express');
const uuid = require('node-uuid');
const { Message,MessageList } = require('../utils/message');
const materialInfoModel = require('../models/material');

const router = express.Router();

router.post('/',(req,res,next)=>{
  const {name,introduction,remark} = req.body;
  const id = uuid.v1();
  const material = new materialInfoModel({id,name,introduction,remark});
  material.save().then(data=>{
    if(data){
      res.json(Message(200,'添加成功！'));
    }
  });
});

router.delete('/',(req,res,next)=>{
  const {id}=req.query;
  if(id){
    materialInfoModel.deleteOne({id}).then(data=>{
      if(data.deletedCount!==0){
        res.json(Message(200,'删除成功！'))
      }else{
        res.json(Message(400,'删除失败'))
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'))
  }
})

router.put('/',(req,res,next)=>{
  const {id}=req.query;
  const {introduction,remark}=req.body;
  if(id){
    materialInfoModel.updateOne({id},{introduction,remark}).then(data=>{
      if(data.acknowledged&&data.modifiedCount!==0){
        res.json(Message(200,'修改成功！'));
      }else{
        res.json(Message(400,'修改失败！'));
      }
    })
  }else{
    res.json(Message(400,'缺少参数id'));
  }
})

router.get('/',(req,res,next)=>{
  const {id,name}=req.query;
  let {page=1,pageSize=10}=req.query;
  let regexp=new RegExp(name,'i');
  const queryObj={};
  if(name) queryObj.$or=[{name:{$regex:regexp}}];
  if(id){ 
    queryObj.id=id;
    materialInfoModel.findOne(queryObj).then(data=>{
      res.json(Message(200,'',data));
    })
    return
  }
  materialInfoModel.find(queryObj).count((err,count)=>{
    materialInfoModel.find(queryObj)
      .limit(pageSize)
      .skip((page-1)*pageSize)
      .then(data=>{
        res.json(MessageList(200,'',data,page,pageSize,count));
    })
  })
})

router.get('/getList',(req,res,next)=>{
  materialInfoModel.find().then(data=>{
    const arr=[];
    data.forEach((item,index)=>{
      if(arr.indexOf(item.name)===-1){
        arr.push(item.name)
      }
    })
    res.json(MessageList(200,'',arr,0,0,arr.length));
  })
})
module.exports = router